package com.stone.serverless.rpc.loadbalancer;

import cn.hutool.core.util.ObjectUtil;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import com.stone.serverless.registry.DiscoveryService;
import com.stone.serverless.registry.domain.ServiceInstance;
import com.stone.serverless.rpc.RpcOkhttpComponentConsumer;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/25 14:48
 * @Version: 1.0.0
 */
public class StoneServerList extends AbstractServerList<StoneServer> {

    private String serviceId;


    @Override
    public List<StoneServer> getInitialListOfServers() {
        return getServers();
    }

    @Override
    public List<StoneServer> getUpdatedListOfServers() {
        return getServers();
    }

    private List<StoneServer> getServers() {
        try {
            //String group = discoveryProperties.getGroup();
            DiscoveryService discoveryService = RpcOkhttpComponentConsumer.INSTANCE.discoveryService;
            if (null==discoveryService) {
                return Collections.emptyList();
            }
            List<ServiceInstance> instances = discoveryService.selectInstances(serviceId, true);
            return instancesToServerList(instances);
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Can not get service instances from nacos, serviceId=" + serviceId,
                    e);
        }
    }

    private List<StoneServer> instancesToServerList(List<ServiceInstance> instances) {
        List<StoneServer> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(instances)) {
            return result;
        }
        for (ServiceInstance instance : instances) {
            result.add(new StoneServer(instance));
        }

        return result;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        this.serviceId = clientConfig.getClientName();
    }
}
